package com.cac.oj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cac.oj.common.ErrorCode;
import com.cac.oj.constant.CommonConstant;
import com.cac.oj.exception.BusinessException;
import com.cac.oj.exception.ThrowUtils;
import com.cac.oj.model.dto.notice.NoticeQueryRequest;
import com.cac.oj.model.entity.Notice;

import com.cac.oj.model.entity.User;
import com.cac.oj.model.vo.NoticeVO;
import com.cac.oj.model.vo.UserVO;
import com.cac.oj.service.NoticeService;
import com.cac.oj.mapper.NoticeMapper;
import com.cac.oj.service.UserService;
import com.cac.oj.utils.SqlUtils;
import com.google.gson.Gson;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author cac_qin
* @description 针对表【notice(公告)】的数据库操作Service实现
* @createDate 2025-04-01 15:35:06
*/
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice>
    implements NoticeService{

    private final static Gson GSON = new Gson();

    @Resource
    private UserService userService;

    /**
     * 校验公告是否合法
     * @param notice
     * @param add
     */
    @Override
    public void validNotice(Notice notice, boolean add) {
        if (notice == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = notice.getTitle();
        String content = notice.getContent();
        Integer submitNum = notice.getSubmitNum();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
        if (submitNum <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "报名人数不能设定小于等于0");
        }
    }
    /**
     * 获取查询包装类
     *
     * @param noticeQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Notice> getQueryWrapper(NoticeQueryRequest noticeQueryRequest) {
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        if (noticeQueryRequest == null) {
            return queryWrapper;
        }
        String title = noticeQueryRequest.getTitle();
        String content = noticeQueryRequest.getContent();
        String sortField = noticeQueryRequest.getSortField();
        String sortOrder = noticeQueryRequest.getSortOrder();
        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public NoticeVO getNoticeVO(Notice notice, HttpServletRequest request) {
        NoticeVO noticeVO = NoticeVO.objToVo(notice);
        // 1. 关联查询用户信息
        Long userId = notice.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        noticeVO.setUserVO(userVO);
        return noticeVO;
    }

    @Override
    public Page<NoticeVO> getNoticeVOPage(Page<Notice> noticePage, HttpServletRequest request) {
        List<Notice> noticeList = noticePage.getRecords();
        Page<NoticeVO> noticeVOPage = new Page<>(noticePage.getCurrent(), noticePage.getSize(), noticePage.getTotal());
        if (CollectionUtils.isEmpty(noticeList)) {
            return noticeVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = noticeList.stream().map(Notice::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<NoticeVO> noticeVOList = noticeList.stream().map(notice -> {
            NoticeVO noticeVO = NoticeVO.objToVo(notice);
            Long userId = notice.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            noticeVO.setUserVO(userService.getUserVO(user));
            return noticeVO;
        }).collect(Collectors.toList());
        noticeVOPage.setRecords(noticeVOList);
        return noticeVOPage;
    }
}




